package com.demo.algorithm.demo5;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * <p>
 * </p>
 *
 * @author yanyg
 * @date 2024/2/17 16:17
 */
public class ServerThread extends Thread {
    //volatile修饰符用来保证其它线程读取的总是该变量的最新的值
    public volatile boolean exit = false;

    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8080);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while(!exit){
            try {
                serverSocket.accept(); //阻塞等待客户端消息
            } catch (IOException e) {
                e.printStackTrace();
            }
            // ...
        }
    }

    public static void main(String[] args) {
        ServerThread t = new ServerThread();
        t.start();
        //...
        t.exit = true; //修改标志位，退出线程
    }
}

